// src/app/workspace/[workspaceId]/_components/preferences-modal.tsx
import React, {useState} from 'react';
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger
} from "@/components/ui/dialog";
import {TrashIcon} from "lucide-react";
import {useUpdateWorkspace} from "@/features/workspaces/api/use-update-workspace";
import {useRemoveWorkspace} from "@/features/workspaces/api/use-remove-workspace";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {toast} from "sonner";
import {useRouter} from "next/navigation";
import UseConfirm from "@/hooks/social/use-confirm";

interface Props {
    open: boolean;
    setOpen: (open: boolean) => void;
    initialValue: string;
}

const PreferencesModal = ({open, setOpen, initialValue}: Props) => {
    const router = useRouter()

    // workspace名称
    const [value, setValue] = useState(initialValue)
    const [editOpen, setEditOpen] = useState(false)

    const {mutate: updateWorkspace, isPending: isUpdating} = useUpdateWorkspace()
    const {mutate: removeWorkspace, isPending: isRemoving} = useRemoveWorkspace()

    const workspaceId = useWorkspaceId()
    const [ConfirmDialog, confirm] = UseConfirm(
        "Are you sure?",
        "This action is irreversible."
    )

    const handleEdit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        await updateWorkspace({
            id: workspaceId as string,
            name: value
        }, {
            onSuccess: () => {
                toast.success('Workspace updated')
                setEditOpen(false)
            },
            onError: () => {
                toast.error("Failed to update workspace")
            }
        })
    }
    const handleRemove = async () => {
        const ok = await confirm()
        if (!ok) return

        await removeWorkspace({id: workspaceId as string}, {
            onSuccess: () => {
                toast.success('Workspace removed')
                // router.replace('/')
            },
            onError: () => {
                toast.error("Failed to remove workspace")
            }
        })
    }

    return (
        <>
            <ConfirmDialog/>
            <Dialog
                open={open}
                onOpenChange={setOpen}
            >
                <DialogContent className={`p-0 bg-gray-50 overflow-hidden`}>
                    <DialogHeader className={`p-4 border-b bg-white`}>
                        <DialogTitle>
                            {value}
                        </DialogTitle>
                    </DialogHeader>
                    <div className={`px-4 pb-4 flex flex-col gap-y-2`}>
                        <Dialog open={editOpen} onOpenChange={setEditOpen}>
                            <DialogTrigger asChild>
                                <div className={`px-5 py-4 bg-white rounded-lg border cursor-pointer
                    hover:bg-gray-50`}>
                                    <div className={`flex items-center justify-between`}>
                                        <p className={`text-sm font-semibold`}>
                                            Workspace name
                                        </p>
                                        <p className={`text-sm text-[#1264a3] hover:underline font-semibold`}>
                                            Edit
                                        </p>
                                    </div>
                                    <p className={`text-sm`}>
                                        {editOpen}
                                    </p>
                                </div>
                            </DialogTrigger>
                            <DialogContent>
                                <DialogHeader>
                                    <DialogTitle>
                                        Rename this workspace
                                    </DialogTitle>
                                </DialogHeader>
                                <form className={`space-y-4`} onSubmit={handleEdit}>
                                    <Input
                                        value={value}
                                        disabled={isUpdating}
                                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                            setValue(e.target.value)}
                                        required
                                        autoFocus
                                        minLength={3}
                                        maxLength={80}
                                        placeholder={'Workspace name e.g. "Work", "Personal", "Home"'}
                                    />
                                    <DialogFooter>
                                        <Button disabled={isUpdating}>
                                            Save
                                        </Button>
                                        <DialogClose asChild>
                                            <Button variant={'destructive'} disabled={isUpdating}>
                                                Cancel
                                            </Button>
                                        </DialogClose>
                                    </DialogFooter>
                                </form>
                            </DialogContent>
                        </Dialog>
                        <button
                            disabled={isRemoving}
                            onClick={handleRemove}
                            className={`flex items-center gap-x-2 px-5 py-4 bg-white rounded-lg
                        border cursor-pointer hover:bg-gray-50 text-rose-600`}
                        >
                            <TrashIcon className={'size-4'}/>
                            <p className={`text-sm font-semibold`}>Delete workspace</p>
                        </button>
                    </div>
                </DialogContent>
            </Dialog>
        </>
    );
};

export default PreferencesModal;
